import datetime,cgi
import sys
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.dist import use_library
from os import environ
from models import *

class Language(webapp.RequestHandler,db.Model):
	def verifyLogin(self):
		user = users.get_current_user()
		if user:
			usercheck=userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					if i.privilege=='admin':
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				self.redirect("/user")
			except:
				path = os.path.join(os.path.dirname(__file__),'form.html')#use template
				self.response.out.write(template.render(path,{"email":user.email()}))#using template
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def get(self):
		self.verifyLogin()
		languages=[]		
		alllanguages=db.GqlQuery("SELECT * FROM languages")
		for language in alllanguages:
			tmp=[]
			tmp.append(language.languageid)
			tmp.append(language.language)
			languages.append(tmp)
			
		path = os.path.join(os.path.dirname(__file__),'language.html')#specify file name
		self.response.out.write(template.render(path,{"list":languages}))#var name 'list' and 'name' is used in html

	def post(self):
		lang=db.GqlQuery("SELECT * FROM languages")
		for i in lang:
			if self.request.get(i.languageid) != i.languageid:
				i.delete()
		langs=self.request.get("addlan")
		langid=langs.split(',')
		for i in langid:
			if i:
				la=languages(language=str(i))
				key=la.put()
				idnum=key.id()
				la.languageid=str(idnum)
				la.put()
		self.redirect("/admin")

application = webapp.WSGIApplication([('/updatelanguage', Language)], debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
